package com.tanhua.dubbo.api.impl.mongo;

import com.tanhua.domain.mongo.RecommendUser;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.dubbo.api.mongo.RecommendUserApi;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service
public class RecommendUserApiImpl implements RecommendUserApi {

    @Autowired
    private MongoTemplate mongoTemplate;


    /**
     * #  查询与1号用户缘分值最高的用户
         db.recommend_user.find({userId:1}).sort({score:-1}).limit(1);
     * @param userId
     * @return
     */
    @Override
    public RecommendUser queryWithMaxScore(long userId) {
        Query query = new Query(Criteria.where("userId").is(userId));
        query.with(Sort.by(Sort.Order.desc("score"))).limit(1);
        RecommendUser recommendUser = mongoTemplate.findOne(query, RecommendUser.class);
        return recommendUser;
    }

    /**
     * //查询用户的推人分页对象
     *
     * //第一页今日佳人,每页10条  跳过条数：（page-1）*pageSize
     db.recommend_user.find({userId:1}).sort({score:-1}).skip(0).limit(10)

     //第二 页今日佳人,每页10条
     db.recommend_user.find({userId:1}).sort({score:-1}).skip(10).limit(10)

     //第三 页今日佳人,每页10条
     db.recommend_user.find({userId:1}).sort({score:-1}).skip(20).limit(10)

     */
    @Override
    public PageResult queryRecommendation(Integer page, Integer pagesize, long userId) {
        Query query = new Query(Criteria.where("userId").is(userId));
        query.with(Sort.by(Sort.Order.desc("score"))).skip((page-1)*pagesize).limit(pagesize);

        long counts = mongoTemplate.count(query, RecommendUser.class);
        List<RecommendUser> recommendUserList = mongoTemplate.find(query, RecommendUser.class);
        PageResult pageResult = new PageResult( page,  pagesize, (int)counts,  recommendUserList);
        return pageResult;
    }

    @Override
    public long queryScore(long userId, Long recommendUserId) {
        Query query = new Query(Criteria.where("userId").is(userId)
        .and("recommendUserId").is(recommendUserId));
        RecommendUser recommendUser = mongoTemplate.findOne(query, RecommendUser.class);
        if(recommendUser==null){
            return 80L;
        }
        return recommendUser.getScore().longValue();
    }
}
